package com.example.lock;

import com.example.mapper.TblLockMapper;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @ClassName MyLock
 * @Description TODO
 * @Author zhaoluowei
 * @Date 2019/8/3  7:34
 * @Version 1.0
 */
@Component
public class MyLock implements Lock {

    private static final int ID_NUM = 1;

    @Autowired
    private TblLockMapper tblLockMapper;

    @Override
    //阻塞式加锁
    public void lock() {
        //尝试加锁
        if (tryLock()) {
            return;
        }

        //加锁失败进行阻塞
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //递归调用重新加锁
        lock();

    }

    @Override
    //数据库的唯一键发送冲突
    public boolean tryLock() {
        try {
            tblLockMapper.inser(ID_NUM);
            System.out.println("加锁");
        } catch (Exception e) {
            return false;
        }


        return true;
    }

    @Override
    public void unlock() {
        System.out.println("解锁");
        tblLockMapper.deletePrimaryKey(ID_NUM);
    }



    @Override
    public void lockInterruptibly() throws InterruptedException {

    }



    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }



    @Override
    public Condition newCondition() {
        return null;
    }
}
